const through = require('through2')
const log = require('./log')
const qiniu = require('./upload/qiniu')
const oss = require('./upload/oss')
const s3 = require('./upload/s3')
const packageJson = require('./package.json')

/**
 * options 七牛参数
 * getFileName 获取文件名的函数
 */
module.exports = (type, options, getFileName) => {
  return through.obj((file, enc, callback) => {
    if(file.isNull()) {
      return callback()
    }
    if(!file.isBuffer()) {
      log.red(`${packageJson.name} File type is not Buffer`)
      return callback()
    }
    if (!options) {
      log.red(`${packageJson.name} Error Parameter[0] does not exist`)
      return callback()
    }
    if (!getFileName) {
      log.red(`${packageJson.name} Error Parameter[1] is not a function`)
      return callback()
    }

    switch (type) {
    case 'qiniu':
      qiniu.upload(file, options, getFileName(file))
      break
    case 'oss':
      oss.upload(file, options, getFileName(file))
      break
    case 's3':
      s3.upload(file, options, getFileName(file))
      break
    default:
      break
    }

    return callback() // 告诉stream引擎，已经处理完成
  })
}
